//
//  UploadPhotoViewController.m
//  myDemo2
//
//  Created by wuxueying on 5/14/14.
//
//

#import "UploadPhotoViewController.h"
#import "TNSexyImageUploadProgress.h"
#import "AFNetworking/AFHTTPRequestOperationManager.h"
#import "AFNetworking/AFHTTPSessionManager.h"

@interface UploadPhotoViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) TNSexyImageUploadProgress *imageUploadProgress;
@end
@implementation UploadPhotoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (IBAction)uploadPhoto:(id)sender {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if( [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront] ){
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:^{}];
}

#define WEBSERVICE_URL @"http://10.10.120.105:3000/files"
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImagePNGRepresentation(selectedImage);
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imageData name:@"uploads" fileName:@"test" mimeType:@"image/png"];
        } error:nil];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSProgress *progress = nil;
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            [progress removeObserver:self forKeyPath:@"fractionCompleted"];
            if (error) {
            } else {
            }
        }];
        
        [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
        
        [uploadTask resume];
        
        self.imageUploadProgress = [[TNSexyImageUploadProgress alloc] init];
        self.imageUploadProgress.radius = 100;
        self.imageUploadProgress.progressBorderThickness = -10;
        self.imageUploadProgress.trackColor = [UIColor blackColor];
        self.imageUploadProgress.progressColor = [UIColor whiteColor];
        self.imageUploadProgress.imageToUpload = selectedImage;
        [self.imageUploadProgress show];
    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
        NSProgress *progress = (NSProgress *)object;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageUploadProgress.progress = progress.fractionCompleted;
        });
        
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

@end
